import userApi, { ILoginData } from "@/apis/userApi";
import { CacheEnum } from "@/enum/userEnum";
import router from "@/router"
import userStore from "@/store/userStore";
import { ElMessage } from "element-plus";
import utils from "./index"
import store from "./store";

//是否是登录状态
export function isLogin(){
  
   return Boolean(store.get(CacheEnum.TOKEN_NAME))
}



//用户登录
export async function login(userName:string, password:string,protect:string,uuid:string){
    
    // const {data:{token}} = await userApi.userLogin(value)

  const ref=  await userApi.userLogin(userName,password,protect,uuid)

  if(ref.msg==="用户认证失败请重新登录"){
    return ElMessage({
         type:"error",
         message:"用户账号或密码错误"
    })
  }
  if(ref.msg==="验证码错误"){
    return ElMessage({
      type:"error",
      message:"验证码错误"
 })
  }
   else{
    utils.store.set(CacheEnum.TOKEN_NAME,ref.data?.token)
     
    //登录成功删除验证码相关信息
      utils.store.remove("UUID-protect")
      utils.store.remove("protect-img")


  await  userStore().getUserInfo(userName,password)
    // 登录成功跳到后后台
      
      const routeName=  sessionStorage.getItem("redirect_router_name") ??"home"  //没有历史路由，重新登录之后掉到home
        //刷新
        sessionStorage.setItem("flash","flash_current_page")
        
        router.push({name:routeName })
           
          ElMessage({
              message: '登录成功',
              type: 'success',
              grouping: true,
            })    
   }    
    }

//用户退出
export  async function logout(){

     const res= (await userApi.userLogout()).msg
    
     if(res=="注销成功"){
//删除token   
utils.store.remove(CacheEnum.TOKEN_NAME)

    router.push({name:"home" }) 
    userStore().info=null
    ElMessage({
        message: '退出成功',
        type: 'success',
        grouping: true,
      })
     }
    
       
    
}


